package com.pl.rabarbar.serv;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.pl.rabarbar.database.DBManager;

public class BookstoreListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		ServletContext ctx = servletContextEvent.getServletContext();
        DBManager dbManager = (DBManager) ctx.getAttribute("DBManager");
        try {
			dbManager.closeConn();
			 System.out.println("Database connection closed for Application.");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
       
	}

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
	ServletContext ctx = servletContextEvent.getServletContext();

		//String url = ctx.getInitParameter("DB_URL"); //bylo minelo :)
		//String u = ctx.getInitParameter("USER");
		//String p = ctx.getInitParameter("PASS");
		//String jdbc = ctx.getInitParameter("JDBC_DRIVER");

		// create database connection from init parameters and set it to context

		DBManager dbManager = null;
		try {
			dbManager = DBManager.getInstance();
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ctx.setAttribute("DBManager", dbManager);
		System.out.println("Database connection initialized for Application.");

	}

}
